import controller.ActivityController;
import controller.UserController;
import model.Activity;
import model.SignUp;
import model.User;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 校园活动管理系统 - 带GUI界面
 */
public class CampusActivitySystem {
    private static JFrame frame;
    private static ActivityController activityController;
    private static UserController userController;

    // 主面板和标签页
    private static JPanel mainPanel;
    private static JTabbedPane tabbedPane;

    // 活动管理面板组件
    private static JTable activityTable;
    private static DefaultTableModel activityTableModel;

    // 学生管理面板组件
    private static JTable studentTable;
    private static DefaultTableModel studentTableModel;

    // 学生报名管理面板组件
    private static JTable signUpTable;
    private static DefaultTableModel signUpTableModel;

    public static void main(String[] args) {
        // 初始化控制器
        activityController = new ActivityController();
        userController = new UserController();

        // 创建GUI
        SwingUtilities.invokeLater(() -> createAndShowGUI());
    }

    private static void createAndShowGUI() {
        // 创建主窗口
        frame = new JFrame("校园活动管理系统");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(900, 600);

        // 创建主面板
        mainPanel = new JPanel(new BorderLayout());

        // 创建标签页
        tabbedPane = new JTabbedPane();

        // 初始化各面板
        initActivityPanel();
        initStudentPanel();
        initSignUpPanel();

        // 添加标签页
        tabbedPane.addTab("活动管理", createActivityPanel());
        tabbedPane.addTab("学生管理", createStudentPanel());
        tabbedPane.addTab("学生报名", createSignUpPanel());

        // 添加标签页到主面板
        mainPanel.add(tabbedPane, BorderLayout.CENTER);

        // 设置主面板
        frame.setContentPane(mainPanel);

        // 显示窗口
        frame.setVisible(true);

        // 加载初始数据
        refreshActivityTable();
        refreshStudentTable();
        refreshSignUpTable();
    }

    // 初始化活动管理面板
    private static void initActivityPanel() {
        activityTableModel = new DefaultTableModel(
                new String[] {"活动ID", "标题", "地点", "开始时间", "结束时间", "报名截止时间"},
                0
        );

        activityTable = new JTable(activityTableModel);
    }

    // 初始化学生管理面板
    private static void initStudentPanel() {
        studentTableModel = new DefaultTableModel(
                new String[] {"学生ID", "用户名", "姓名"},
                0
        );

        studentTable = new JTable(studentTableModel);
    }

    // 初始化学生报名管理面板
    private static void initSignUpPanel() {
        signUpTableModel = new DefaultTableModel(
                new String[] {"学生ID", "学生姓名", "活动ID", "活动标题", "报名时间"},
                0
        );

        signUpTable = new JTable(signUpTableModel);
    }

    // 创建活动管理面板
    private static JPanel createActivityPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 添加表格
        JScrollPane scrollPane = new JScrollPane(activityTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel();

        JButton addButton = new JButton("添加活动");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddActivityDialog();
            }
        });

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshActivityTable();
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(refreshButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    // 创建学生管理面板
    private static JPanel createStudentPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 添加表格
        JScrollPane scrollPane = new JScrollPane(studentTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel();

        JButton addButton = new JButton("添加学生");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddStudentDialog();
            }
        });

        JButton viewButton = new JButton("查看学生信息");
        viewButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showStudentInfoDialog();
            }
        });

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshStudentTable();
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(viewButton);
        buttonPanel.add(refreshButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    // 创建学生报名管理面板
    private static JPanel createSignUpPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 添加表格
        JScrollPane scrollPane = new JScrollPane(signUpTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel();

        JButton addButton = new JButton("添加报名");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showAddSignUpDialog();
            }
        });

        JButton deleteButton = new JButton("取消报名");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteSelectedSignUp();
            }
        });

        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshSignUpTable();
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    // 刷新活动表格
    private static void refreshActivityTable() {
        activityTableModel.setRowCount(0);

        List<Activity> activities = activityController.getAllActivities();
        for (Activity activity : activities) {
            activityTableModel.addRow(new Object[] {
                    activity.getActivityId(),
                    activity.getTitle(),
                    activity.getLocation(),
                    activity.getStartTime(),
                    activity.getEndTime(),
                    activity.getSignUpEndTime()
            });
        }
    }

    // 刷新学生表格
    private static void refreshStudentTable() {
        studentTableModel.setRowCount(0);

        List<User> students = userController.getAllStudents();
        for (User student : students) {
            studentTableModel.addRow(new Object[] {
                    student.getUserId(),
                    student.getUsername(),
                    student.getName()
            });
        }
    }

    // 刷新报名表格
    private static void refreshSignUpTable() {
        signUpTableModel.setRowCount(0);

        List<SignUp> signUps = activityController.getAllSignUps();
        for (SignUp signUp : signUps) {
            User user = userController.getUserById(signUp.getUserId());
            Activity activity = activityController.getActivityById(signUp.getActivityId());

            if (user != null && activity != null) {
                signUpTableModel.addRow(new Object[] {
                        signUp.getUserId(),
                        user.getName(),
                        signUp.getActivityId(),
                        activity.getTitle(),
                        signUp.getSignUpTime()
                });
            }
        }
    }

    // 显示添加活动对话框
    private static void showAddActivityDialog() {
        JDialog dialog = new JDialog(frame, "添加活动", true);
        dialog.setSize(500, 400);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = new JPanel(new GridLayout(7, 2, 10, 10));

        // 创建表单组件
        JTextField idField = new JTextField();
        JTextField titleField = new JTextField();
        JTextField locationField = new JTextField();
        JTextField startField = new JTextField();
        JTextField endField = new JTextField();
        JTextField signUpEndField = new JTextField();
        JTextField maxParticipantsField = new JTextField();

        // 添加组件到面板
        panel.add(new JLabel("活动ID:"));
        panel.add(idField);
        panel.add(new JLabel("活动标题:"));
        panel.add(titleField);
        panel.add(new JLabel("活动地点:"));
        panel.add(locationField);
        panel.add(new JLabel("开始时间 (yyyy-MM-dd HH:mm):"));
        panel.add(startField);
        panel.add(new JLabel("结束时间 (yyyy-MM-dd HH:mm):"));
        panel.add(endField);
        panel.add(new JLabel("报名截止时间 (yyyy-MM-dd HH:mm):"));
        panel.add(signUpEndField);
        panel.add(new JLabel("最大参与人数:"));
        panel.add(maxParticipantsField);

        // 添加按钮
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取输入值
                String id = idField.getText();
                String title = titleField.getText();
                String location = locationField.getText();
                String startTime = startField.getText();
                String endTime = endField.getText();
                String signUpEndTime = signUpEndField.getText();
                int maxParticipants = 0;

                try {
                    maxParticipants = Integer.parseInt(maxParticipantsField.getText());
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(frame, "请输入有效的最大参与人数", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 验证输入
                if (id.isEmpty() || title.isEmpty() || location.isEmpty() ||
                        startTime.isEmpty() || endTime.isEmpty() || signUpEndTime.isEmpty()) {
                    JOptionPane.showMessageDialog(frame, "请填写所有必填字段", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 转换日期
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Timestamp startTimestamp = null;
                Timestamp endTimestamp = null;
                Timestamp signUpEndTimestamp = null;

                try {
                    startTimestamp = new Timestamp(sdf.parse(startTime).getTime());
                    endTimestamp = new Timestamp(sdf.parse(endTime).getTime());
                    signUpEndTimestamp = new Timestamp(sdf.parse(signUpEndTime).getTime());
                } catch (ParseException ex) {
                    JOptionPane.showMessageDialog(frame, "日期格式不正确，请使用 yyyy-MM-dd HH:mm 格式", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 创建活动
                Activity activity = new Activity();
                activity.setActivityId(id);
                activity.setTitle(title);
                activity.setLocation(location);
                activity.setStartTime(startTimestamp);
                activity.setEndTime(endTimestamp);
                activity.setSignUpEndTime(signUpEndTimestamp);
                activity.setMaxParticipants(maxParticipants);
                activity.setCurrentParticipants(0);

                // 保存活动
                if (activityController.addActivity(activity)) {
                    JOptionPane.showMessageDialog(frame, "活动添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshActivityTable();
                    dialog.dispose();
                } else {
                    JOptionPane.showMessageDialog(frame, "活动添加失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setVisible(true);
    }

    // 显示添加学生对话框
    private static void showAddStudentDialog() {
        JDialog dialog = new JDialog(frame, "添加学生", true);
        dialog.setSize(400, 200);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = new JPanel(new GridLayout(4, 2, 10, 10));

        JTextField userIdField = new JTextField();
        JTextField usernameField = new JTextField();
        JTextField nameField = new JTextField();

        panel.add(new JLabel("学生ID:"));
        panel.add(userIdField);
        panel.add(new JLabel("用户名:"));
        panel.add(usernameField);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String userId = userIdField.getText();
                String username = usernameField.getText();
                String name = nameField.getText();

                if (userId.isEmpty() || username.isEmpty() || name.isEmpty()) {
                    JOptionPane.showMessageDialog(frame, "请填写所有字段", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                User student = new User();
                student.setUserId(userId);
                student.setUsername(username);
                student.setName(name);
                student.setRole(0); // 0表示学生

                if (userController.addStudent(student)) {
                    JOptionPane.showMessageDialog(frame, "学生添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshStudentTable();
                    dialog.dispose();
                } else {
                    JOptionPane.showMessageDialog(frame, "学生添加失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setVisible(true);
    }

    // 显示学生信息对话框
    private static void showStudentInfoDialog() {
        int selectedRow = studentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(frame, "请先选择一个学生", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String studentId = (String) studentTableModel.getValueAt(selectedRow, 0);
        User student = userController.getUserById(studentId);

        if (student == null) {
            JOptionPane.showMessageDialog(frame, "学生不存在", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(frame, "学生信息", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = new JPanel(new GridLayout(6, 2, 10, 10));

        panel.add(new JLabel("学生ID:"));
        panel.add(new JTextField(student.getUserId()));

        panel.add(new JLabel("用户名:"));
        panel.add(new JTextField(student.getUsername()));

        panel.add(new JLabel("姓名:"));
        panel.add(new JTextField(student.getName()));

        // 显示该学生报名的活动
        List<SignUp> signUps = activityController.getSignUpsByStudentId(studentId);
        StringBuilder activityList = new StringBuilder();
        for (SignUp signUp : signUps) {
            Activity activity = activityController.getActivityById(signUp.getActivityId());
            if (activity != null) {
                activityList.append(activity.getTitle())
                        .append(" (")
                        .append(activity.getActivityId())
                        .append(")\n");
            }
        }

        panel.add(new JLabel("已报名活动:"));
        JTextArea activitiesArea = new JTextArea(activityList.toString());
        activitiesArea.setEditable(false);
        panel.add(new JScrollPane(activitiesArea));

        JPanel buttonPanel = new JPanel();
        JButton closeButton = new JButton("关闭");

        closeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });

        buttonPanel.add(closeButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setVisible(true);
    }

    // 显示添加报名对话框
    private static void showAddSignUpDialog() {
        JDialog dialog = new JDialog(frame, "添加报名", true);
        dialog.setSize(400, 200);
        dialog.setLocationRelativeTo(frame);

        JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));

        JTextField studentIdField = new JTextField();
        JTextField activityIdField = new JTextField();

        panel.add(new JLabel("学生ID:"));
        panel.add(studentIdField);
        panel.add(new JLabel("活动ID:"));
        panel.add(activityIdField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String studentId = studentIdField.getText();
                String activityId = activityIdField.getText();

                if (studentId.isEmpty() || activityId.isEmpty()) {
                    JOptionPane.showMessageDialog(frame, "请填写学生ID和活动ID", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 验证学生和活动是否存在
                User student = userController.getUserById(studentId);
                Activity activity = activityController.getActivityById(activityId);

                if (student == null) {
                    JOptionPane.showMessageDialog(frame, "学生ID不存在", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (activity == null) {
                    JOptionPane.showMessageDialog(frame, "活动ID不存在", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (activityController.signUpActivity(studentId, activityId)) {
                    JOptionPane.showMessageDialog(frame, "报名成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshSignUpTable();
                    refreshActivityTable();  // 更新活动参与人数
                    dialog.dispose();
                } else {
                    JOptionPane.showMessageDialog(frame, "报名失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dialog.dispose();
            }
        });

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setVisible(true);
    }

    // 删除选中的报名
    private static void deleteSelectedSignUp() {
        int selectedRow = signUpTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(frame, "请先选择要取消的报名记录", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        String studentId = (String) signUpTableModel.getValueAt(selectedRow, 0);
        String activityId = (String) signUpTableModel.getValueAt(selectedRow, 2);

        int confirm = JOptionPane.showConfirmDialog(frame,
                "确定要取消该学生的报名吗?", "确认", JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            if (activityController.cancelSignUp(studentId, activityId)) {
                JOptionPane.showMessageDialog(frame, "取消报名成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                refreshSignUpTable();
                refreshActivityTable();  // 更新活动参与人数
            } else {
                JOptionPane.showMessageDialog(frame, "取消报名失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}